//
//  CBCentralViewController.swift
//  SwiftLearnAll
//
//  Created by iosdev1 on 2017/8/3.
//  Copyright © 2017年 ygsoft. All rights reserved.
//

import UIKit
import CoreBluetooth

class CBCentralViewController: ZyBaseViewController, CBCentralManagerDelegate, CBPeripheralDelegate{

    var tfdStr = "空数据";
    let SERVICE_UUID = "0000ffe0-0000-1000-8000-00805f9b34fb"
    let CHARACTERISTIC_UUID = "0000ffe1-0000-1000-8000-00805f9b34fb"
//    let SERVICE_UUID = "CDD1"
//    let CHARACTERISTIC_UUID = "CDD2"

    var cbCentralManager:CBCentralManager?
    var cbPeripheral:CBPeripheral?
    var cbCharacteristic:CBCharacteristic?

    var alert:UIAlertController = UIAlertController.init(title: "请选择要连接的蓝牙", message: "测试专用", preferredStyle: UIAlertControllerStyle.actionSheet);
    var arrAlert:Array<String> = Array.init()
    var arrCentralManager:Array<CBCentralManager> = Array.init()
    var arrPeripheral:Array<CBPeripheral> = Array.init()
    var timer:Timer? = nil

    @IBOutlet weak var tfdInput: UITextField!
    @IBOutlet weak var btnGet: UIButton!
    @IBOutlet weak var btnSend: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.title = "蓝牙中心设备"
        self.setMyCentral()
    }

    @IBAction func tfdEditingDidEnd(_ sender: UITextField) {
        if (sender.text != nil) {
            tfdStr = sender.text!;
        }
    }

    @IBAction func btnSendClick(_ sender: UIButton) {
        self.view.endEditing(true);
        print("发送\(tfdStr)")
        let data:Data = tfdInput.text!.data(using: String.Encoding.utf8)!;
        cbPeripheral?.writeValue(data, for: cbCharacteristic!, type: CBCharacteristicWriteType.withResponse);
    }

    @IBAction func btnGetClick(_ sender: UIButton) {
        self.view.endEditing(true);
        print("接收\(tfdStr)")
        cbPeripheral?.readValue(for: cbCharacteristic!)
    }


    func setMyCentral() -> Void {
        cbCentralManager = CBCentralManager.init(delegate: self, queue: DispatchQueue.main)
    }
    /** 判断手机蓝牙状态
     CBManagerStateUnknown = 0,  未知
     CBManagerStateResetting,    重置中
     CBManagerStateUnsupported,  不支持
     CBManagerStateUnauthorized, 未验证
     CBManagerStatePoweredOff,   未启动
     CBManagerStatePoweredOn,    可用
     */
    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        if #available(iOS 10.0, *) {
            if central.state == CBManagerState.poweredOn {
                zyUIshowMessage(message: "蓝牙可用")

                // 根据SERVICE_UUID来扫描外设，如果不设置SERVICE_UUID，则扫描所有蓝牙设备
                central.scanForPeripherals(withServices: [CBUUID.init(string: SERVICE_UUID)], options: nil)
//                central.scanForPeripherals(withServices: nil, options: nil)
                timer = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(timerClick), userInfo: "timer", repeats: false)
            }else if central.state == CBManagerState.unsupported {
                zyUIshowMessage(message: "该设备不支持蓝牙")
            }else if central.state == CBManagerState.poweredOff {
                zyUIshowMessage(message: "蓝牙已关闭")
            }
        } else {
            // Fallback on earlier versions
        }
    }

    /** 发现符合要求的外设，回调 */
    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
        // 对外设对象进行强引用
        cbPeripheral = peripheral
        if (cbPeripheral?.name != nil) {
            let nameStr = cbPeripheral?.name
            // 可以根据外设名字来过滤外设
            print("\(String(describing: nameStr)))");
            if !(arrAlert.contains(nameStr!)) && (nameStr != "zyy.mac"){
                arrAlert.append((cbPeripheral?.name)!);
                arrCentralManager.append(central);
                arrPeripheral.append(peripheral)
            }
        }else{
            print("无姓名")
        }
    }

    /** 连接成功 */
    func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
        // 可以停止扫描
        cbCentralManager?.stopScan()
        // 设置代理
        peripheral.delegate = self;
// 根据UUID来寻找服务
        peripheral.discoverServices([CBUUID.init(string: SERVICE_UUID)])
//        peripheral.discoverServices(nil)
        print("连接\(String(describing: peripheral.name!))成功")
    }

    /** 连接失败的回调 */
    func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
        print("连接失败");
    }

    func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
        print("断开连接")
        // 断开连接可以设置重新连接
        central.connect(peripheral, options: nil)
    }

//    MARK: CBPeripheralDelegate

/** 发现服务 */
    func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
        for service:CBService in peripheral.services! {
            print("所有服务：\(service)")
        }

        // 这里仅有一个服务，所以直接获取
        let service:CBService = (peripheral.services?.last)!
        peripheral.discoverCharacteristics([CBUUID.init(string: CHARACTERISTIC_UUID)], for: service);
//        peripheral.discoverCharacteristics(nil, for: service)
    }

    /** 发现特征回调 */
    func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
        for characteristic:CBCharacteristic in service.characteristics! {
            // 从外设开发人员那里拿到不同特征的UUID，不同特征做不同事情，比如有读取数据的特征，也有写入数据的特征
            print("所有特征\(characteristic)");
        }

        // 这里只获取一个特征，写入数据的时候需要用到这个特征
        cbCharacteristic = service.characteristics?.last;

        // 直接读取这个特征数据，会调用didUpdateValueForCharacteristic
        peripheral.readValue(for: cbCharacteristic!);

        // 订阅通知
        peripheral.setNotifyValue(true, for: cbCharacteristic!);

    }

/** 订阅状态的改变 */
    func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) {
        if (error != nil) {
            print("订阅失败:\(String(describing: error))")
        }

        if characteristic.isNotifying {
            print("订阅成功")
        }else{
            print("订阅失败")
        }
    }

    /** 接收到数据回调 */
    func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
// 拿到外设发送过来的数据
        let data:Data = characteristic.value!
        self.tfdInput.text = String.init(data: data, encoding: String.Encoding.utf8)
    }

    /** 写入数据回调 */
    func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
        if (error != nil) {
            print("写入错误")
        }else{
            print("写入错误")
        }
    }

    func timerClick() {
        cbCentralManager?.stopScan()
        for name in arrAlert {
            let alertAction:UIAlertAction = UIAlertAction.init(title: name, style: UIAlertActionStyle.default) { (action:UIAlertAction) in
                // 连接外设
                let i = self.arrAlert.index(of: name);
                let central:CBCentralManager = self.arrCentralManager[i!];
                let peripheral:CBPeripheral = self.arrPeripheral[i!]
                self.cbPeripheral = peripheral
                central.connect(peripheral, options: nil)
            };
            alert.addAction(alertAction);
        }
        let alertActionCancel:UIAlertAction = UIAlertAction.init(title: "取消", style: UIAlertActionStyle.default) { (action:UIAlertAction) in

        };
        alert.addAction(alertActionCancel)
        self.present(alert, animated: true, completion: nil)
    }

    deinit {
        echo(data: "内存释放");
        timer = nil
    }
}
